<!--
 * @Author: [kangjie]
 * @Date: 2022-04-20 14:58:13
 * @LastEditors: 灰佳小白 1150248441@qq.com
 * @LastEditTime: 2022-10-14 09:19:22
 * @Description:
-->
<!--
 * @Author: [kangjie]
 * @Date: 2022-10-10 09:49:20
 * @LastEditors: 灰佳小白 1150248441@qq.com
 * @LastEditTime: 2022-10-12 10:06:32
 * @Description:
-->
<template>
  <div>
    <!-- 第一行 表单控件按钮 -->
    <div class="header">
      <el-form :inline="true" :model="params" class="demo-form-inline">
        <el-form-item>
          <el-button type="primary" @click="toAdd">添加</el-button>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="params.name"
            placeholder="请输入产品名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="params.status" clearable placeholder="请选择状态">
            <el-option label="正常" value="正常" />
            <el-option label="下架" value="下架" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="params.productCategoryId"
            placeholder="请选择所属栏目"
            clearable
          >
            <el-option
              v-for="item in columns"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 第一行结束 表单控件按钮 -->
    <!-- 第二行 表格 -->
    <el-table v-loading="loading" :data="productData" style="width: 100%">
      <el-table-column type="index" :index="1" label="序号" />
      <el-table-column prop="id" label="产品编号" width="180" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="photo" label="图片">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="right">
            <img slot="reference" :src="scope.row.photo" width="30px" alt="加载失败">
            <img :src="scope.row.photo" width="200px" alt="">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" />
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.status === '正常'"
            type="success"
          >正常</el-tag>
          <el-tag v-else type="danger">下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="category.name" label="所属栏目" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <a href="#" class="toEdit" @click="toEdit(scope.row)">编辑</a>
          <a
            v-if="scope.row.status === '正常'"
            href="#"
            class="offline"
            @click.prevent="changeStatus(scope.row.id, '下架')"
          >下架</a>
          <a
            v-else
            href="#"
            class="online"
            @click.prevent="changeStatus(scope.row.id, '上架')"
          >上架</a>
        </template>
      </el-table-column>
    </el-table>
    <!-- 第二行结束  -->
    <!-- 第三行 分页按钮 -->
    <div class="page">
      <el-pagination
        :current-page="params.page"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 第三行结束 分页按钮 -->
    <!-- 添加和编辑模态框 -->
    <el-dialog :title="title" :visible.sync="visible" @close="toClose">
      <el-form ref="myForm" :rules="rules" :model="form">
        <el-form-item
          label="产品名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="所属栏目"
          :label-width="formLabelWidth"
          prop="productCategoryId"
        >
          <el-select
            v-model="form.productCategoryId"
            clearable
            placeholder="请选择所属栏目"
          >
            <el-option
              v-for="item in columns"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
          <el-input v-model.number="form.price" autocomplete="off" />
        </el-form-item>
        <el-form-item label="封面" :label-width="formLabelWidth" prop="photo">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="form.photo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="产品描述" :label-width="formLabelWidth">
          <el-input v-model="form.description" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="toClose">取 消</el-button>
        <el-button type="primary" @click="toSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { pageQuery, offline, online, saveOrUpdate } from '@/api/product'
import { uploadFileURL } from '@/utils/config'
export default {
  data() {
    return {
      // 图片上传路径
      uploadFileURL,
      // 表单对象 和 分页数据
      params: {
        page: 1,
        pageSize: 10
      },
      // 控制白屏加载动画
      loading: false,
      // 产品数据
      productData: [],
      // 产品总条数
      total: 0,
      // 模态框标题
      title: '',
      // 控制模态框显示与隐藏变量
      visible: false,
      // 表单对象
      form: {},
      formLabelWidth: '120px',
      // 头像上传图片变量
      imageUrl: '',
      // 表单校验规则
      rules: {
        name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
        price: [
          {
            required: true,
            message: '请输入价格并且只能数字',
            trigger: 'blur',
            type: 'number'
          }
        ],
        photo: [{ required: true, message: '请上传封面', trigger: 'change' }],
        productCategoryId: [
          { required: true, message: '请选择栏目', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['columns'])
  },
  created() {
    // 查询到所有栏目 --分发栏目动作
    // 1.使用dispatch方法
    this.$store.dispatch('column/queryColumns', { page: 1, pageSize: 1000 })
    this.getProduct()
  },
  // watch:{
  //   params:{
  //     // pageSize page
  //     handler(){
  //       this.getProduct();
  //     },
  //     deep:true
  //   }
  // },
  methods: {
    // 模态框关闭的回调
    toClose() {
      // 重置表单验证
      setTimeout(() => {
        this.visible = false
        this.form = {}
        this.$refs.myForm.resetFields()
      }, 500)
    },
    // 保存或更新
    toSubmit() {
      // 校验表单
      this.$refs.myForm.validate(async(valid) => {
        if (valid) {
          // 发送保存或更新请求
          const res = await saveOrUpdate(this.form)
          this.$notify({
            type: 'success',
            message: res.message
          })
          this.getProduct()
          this.toClose()
        } else {
          return false
        }
      })
    },
    // 去编辑
    toEdit(row) {
      this.title = '修改产品信息'
      this.visible = true
      this.form = { ...row }
      this.imageUrl = this.form.photo
    },
    // 添加的方法
    toAdd() {
      this.visible = true
      this.title = '添加产品信息'
      this.form = {}
      this.imageUrl = ''
    },
    // 图片上传成功的方法
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      // console.log(res);// {msg,data--图片保存在服务器的地址}
      this.form.photo = res.data
    },
    // 图片上传之前的方法
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 执行上架和下架
    changeStatus(id, status) {
      // 提示用户
      this.$confirm('此操作将更改产品状态, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          if (status === '上架') {
            const res = await online({ id })
            // let res = awiat get(url--上架url,{id})
            this.$message({
              type: 'success',
              message: res.message
            })
          } else {
            const res = await offline({ id })
            this.$message({
              type: 'success',
              message: res.message
            })
          }
          // 刷新页面
          this.getProduct()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },
    // ...mapActions('column',['queryColumns'])
    // 去查询
    onSearch() {
      this.params.page = 1
      this.getProduct()
    },
    // 分页查询产品数据方法
    async getProduct() {
      // 数据获取之前加载动画
      this.loading = true
      for (const key in this.params) {
        // key--属性名
        // this.params[key] --属性值
        if (!this.params[key]) {
          delete this.params[key]
        }
      }
      const res = await pageQuery(this.params)
      this.productData = res.data.list
      this.total = res.data.total
      // 关闭加载动画
      this.loading = false
    },
    // 页码条数发生改变的方法 默认参数pageSize
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize
      this.params.page = 1
      this.getProduct()
    },
    // 当前页码发生改变触发的方法 默认参数page
    handleCurrentChange(page) {
      this.params.page = page
      this.getProduct()
    }
  }
}
</script>
<style lang="scss">
$color: #e65d6e;
a {
  margin-right: 10px;
}
.toEdit,
.online {
  color: #30b08f;
}
.offline {
  color: $color;
}
</style>
